﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PhoneDBModel;
using System.Text.RegularExpressions;

public partial class AddContact : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        PhoneDBEntities dbe = new PhoneDBEntities();
        User usr = dbe.Users.Where(u => u.UserName == Name.Value.Trim()).FirstOrDefault();
        Contact cont = new Contact();
        if (usr != null)
        {
            cont.UserId = usr.Id;
        }
        else
        {
            Regex isHexDigit = new Regex("[\\d]+", RegexOptions.Compiled);
            string newnum = "";
            string input = Phone.Value.Trim();
            foreach (char c in input)
            {
                if (isHexDigit.IsMatch(c.ToString()))
                    newnum += c.ToString();
            }

            cont.Name = Name.Value.Trim();
            cont.Phone = newnum;
            cont.Email = Email.Value.Trim();
        }
        cont.OwnerId = SessionHandler.AuthUser.Id;
        dbe.Contacts.AddObject(cont);
        dbe.SaveChanges();

        ClientScript.RegisterStartupScript(this.GetType(), "onl", "parent.reloadContacts();parent.$.fancybox.close();", true);
    }
}